package com.cw.controller;

import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.cw.common.Constants;
import com.cw.common.R;
import com.cw.config.JwtConfig;
import com.cw.entity.Windows;
import com.cw.entity.dto.WindowsDto;
import com.cw.service.WindowsService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Objects;

/**
 * @author Nice_BernardShaw
 * @date 2022/11/9 0:57
 */
@RestController
@RequestMapping("/windows")
@Slf4j
public class WindowsController {
    @Autowired
    private WindowsService windowsService;

    @GetMapping("/list")
    public R windowsList() {
        return R.success(this.windowsService.getList());
    }

    @GetMapping("/page")
    public R page(@RequestParam(name = "page") Integer page,
                  @RequestParam(name = "pageSize") Integer pageSize,
                  @RequestParam(name = "name", required = false) String name) {
        log.info("page:{},pageSize:{},name:{}", page, pageSize, name);
        Page<WindowsDto> windowsDtoPage = new Page<>(page, pageSize);
        return R.success(this.windowsService.queryPage(windowsDtoPage, name));
    }
    @PostMapping()
    public R save(@RequestBody Windows windows, HttpServletRequest request) {
        if(!JwtConfig.getCurrentId(request).equals(Constants.ADMIN_ID)){
            return R.error("请提升至管理员权限");
        }
        boolean save = this.windowsService.save(windows);
        return R.success(save);
    }
    @PutMapping()
    public R update(@RequestBody Windows windows, HttpServletRequest request) {
        if (!JwtConfig.getCurrentId(request).equals(Constants.ADMIN_ID)){
            return R.error("请提升至管理员权限");
        }
        boolean update = this.windowsService.updateById(windows);
        return R.success(update);
    }
    @GetMapping("/status/{id}")
    public R updateStatus(@PathVariable Integer id,@RequestParam(value = "type")Integer type){
        Windows byId = this.windowsService.getById(id);
        LambdaUpdateWrapper<Windows> wrapper = new LambdaUpdateWrapper<>();
        if(type.equals(Constants.INTEGER_ONE)){
            wrapper.set(Windows::getIsEnable,Objects.equals(byId.getIsEnable(), Constants.STRING_ONE) ? Constants.INTEGER_ZERO : Constants.STRING_ONE)
                    .eq(Windows::getId,id);
        }else {
            wrapper.set(Windows::getIsDeleted,Objects.equals(byId.getIsDeleted(), Constants.INTEGER_ONE) ? Constants.INTEGER_ZERO : Constants.STRING_ONE)
                    .eq(Windows::getId,id);
        }
        boolean b = this.windowsService.update(wrapper);
        return R.success(b);
    }
}
